package com.five.sso.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dypnsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeRequest;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeResponse;
import com.five.sso.config.AliyunConfig;
import com.google.gson.Gson;

import darabonba.core.client.ClientOverrideConfiguration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * 阿里云短信验证码工具类（仅需传入手机号即可发送）
 */
@Slf4j
@Component
public class AliyunSmsVerifyUtils {

    // 固定配置（也可移到配置文件）
    private static final String ENDPOINT = "dypnsapi.aliyuncs.com";
    private static final int DEFAULT_TIMEOUT = 10; // 超时时间（秒）
    private static final int CODE_LENGTH = 6; // 验证码长度

    // 从配置类注入核心配置（无需手动传）
    @Resource
    private AliyunConfig aliyunConfig;

    // 短信相关配置（建议放配置文件，这里用@Value绑定）
    @Value("${sms.sign-name:速通互联验证码}") // 短信签名（默认值可修改）
    private String signName;

    @Value("${sms.template-code:100001}") // 模板CODE（默认值可修改）
    private String templateCode;

    @Value("${sms.valid-min:5}") // 验证码有效期（分钟，默认5分钟）
    private String validMin;

    private AsyncClient asyncClient;
    private final Random random = new Random();

    /**
     * 初始化客户端（Spring启动后自动执行）
     */
    @PostConstruct
    public void initClient() {
        // 从AliyunConfig获取密钥（已通过配置文件加载）
        String accessKeyId = aliyunConfig.getAccessKeyId();
        String accessKeySecret = aliyunConfig.getAccessKeySecret();

        // 构建凭证
        StaticCredentialProvider credentialProvider = StaticCredentialProvider.create(
                Credential.builder()
                        .accessKeyId(accessKeyId)
                        .accessKeySecret(accessKeySecret)
                        .build()
        );

        // 初始化客户端
        this.asyncClient = AsyncClient.builder()
                .credentialsProvider(credentialProvider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(ENDPOINT)
                                .setConnectTimeout(Duration.ofSeconds(DEFAULT_TIMEOUT))
                )
                .build();

        log.info("阿里云短信客户端初始化成功");
    }

    /**
     * 发送短信验证码（核心方法：仅需传入手机号）
     * @param phoneNumber 接收验证码的手机号
     * @return 验证码（用于后续验证比对）
     * @throws Exception 发送异常
     */
    public String sendSmsVerifyCode(String phoneNumber,String code) throws Exception {

        // 构建模板参数（替换##code##为实际验证码）
        String templateParam = String.format("{\"code\":\"%s\",\"min\":\"%s\"}", code, validMin);

        // 构建请求
        SendSmsVerifyCodeRequest request = SendSmsVerifyCodeRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumber(phoneNumber)
                .templateParam(templateParam)
                .build();

        // 同步发送请求
        CompletableFuture<SendSmsVerifyCodeResponse> future = asyncClient.sendSmsVerifyCode(request);
        SendSmsVerifyCodeResponse response = future.get();

        log.info("短信发送成功，手机号：{}，响应：{}", phoneNumber, new Gson().toJson(response));
        return code; // 返回验证码，方便后续存Redis等做验证
    }

    /**
     * 异步发送短信验证码（可选）
     * @param phoneNumber 手机号
     * @return 包含验证码的异步结果
     */
    public CompletableFuture<String> sendSmsVerifyCodeAsync(String phoneNumber,String code) {

        String templateParam = String.format("{\"code\":\"%s\",\"min\":\"%s\"}", code, validMin);

        SendSmsVerifyCodeRequest request = SendSmsVerifyCodeRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumber(phoneNumber)
                .templateParam(templateParam)
                .build();

        return asyncClient.sendSmsVerifyCode(request)
                .whenComplete((resp, ex) -> {
                    if (ex != null) {
                        log.error("异步发送短信失败，手机号：{}", phoneNumber, ex);
                    } else {
                        log.info("异步短信发送成功，手机号：{}", phoneNumber);
                    }
                })
                .thenApply(resp -> code);
    }

//    /**
//     * 生成6位随机验证码
//     */
//    private String generateVerifyCode() {
//        StringBuilder code = new StringBuilder();
//        for (int i = 0; i < CODE_LENGTH; i++) {
//            code.append(random.nextInt(10)); // 0-9随机数
//        }
//        return code.toString();
//    }

    /**
     * 销毁客户端（应用关闭时自动执行）
     */
    @PreDestroy
    public void closeClient() {
        if (asyncClient != null) {
            try {
                asyncClient.close();
                log.info("阿里云短信客户端已关闭");
            } catch (Exception e) {
                log.error("关闭短信客户端失败", e);
            }
        }
    }
}